// Agent sample_agent in project skygarden

/* Initial beliefs and rules */
available(vegetable,36).
need_buy :- available(vegetable,N) & N==0.
setOfVeg([]).

carrying(vegetable,18). // number of vegetables in garden
negative :- carrying(vegetable,N) & N == 0.
started.


/* Initial goals */
!init.
!goto_gate.

/* Plans */

+add(V) : true
	<-	?setOfVeg(S);
		-+setOfVeg([V|S]).
	
+infoAboutVeg(Alive,Gray) : Alive == 0 & Gray == 0 & not started
	<-	.print("Garden is now empty.");
		-+carrying(vegetable,18);
		+started;
		math.closest_pos(0,_,_,_,_);
		-+setOfVeg([]);
		!init;
		!goto_gate.
	
+infoAboutVeg(Alive,Gray).
	
+!init : true
	<-	drop_vegetable(r1);
		?available(vegetable,N);
		-+available(vegetable,N-18);
		.print("I'm coming!").
	
+!goto_gate : not at(r1,garden)
	<- 	move_to(r1,garden);
		!goto_gate.
    
+!goto_gate : at(r1,garden)
	<-	.print("I'm in garden. Now planting...");
		!find_planting_pos.

+!find_planting_pos : not pos(_,_)
	<-	!find_planting_pos.

+!find_planting_pos : not negative & pos(X,Y) & carrying(vegetable,N) & math.closest_pos(N,X,Y,X1,Y1)
	<-	math.get_direction(1,X,Y,X1,Y1,D);
		do(D);
		!planting_at(X1,Y1);
		!find_planting_pos.
		
+!find_planting_pos : not negative
	<-	do(up);
		!find_planting_pos.
		
+!find_planting_pos : true
	<-	-started;
		-infoAboutVeg(_,_);
		-add(_);
		?setOfVeg(S);
		.send([r2,r3],tell,setOfVeg(S));
		// finished found, go to home and wait there
		.print("Finished !Now go home !!");
		!goto_home.
	
+!goto_home : not at(r1,home) & pos(X,Y)
	<-	math.get_direction(1,X,Y,1,17,D);
		do(D);
		!goto_home.
		
+!goto_home : not pos(_,_)
	<- !goto_home.
		
+!goto_home : at(r1,home) & not need_buy & not bought_vegetable
	<-	.broadcast(tell,finished_planting);
		.print("I'm at home and waiting for planting!!").

+!goto_home : at(r1,home) & not need_buy & bought_vegetable
	<-	update_store(r1,36);
		-bought_vegetable.

+!goto_home : need_buy
	<-	.print("There is no vegetable in store.I need more vegetables. Going to supermarket....");
		.broadcast(tell,finished_planting);
		!goto_provider.

+!goto_provider : not at(r1,provider)
	<-	move_to(r1,provider);
		!goto_provider.

+!goto_provider : at(r1,provider)
	<-	.print("I'm in supermarket. Importing...");
		-+available(vegetable,36);
		+bought_vegetable;
		.wait(3000);
		.print("Import is finished. Now I'm go home.");
		!goto_home.
	
@planting_vegetable
+!planting_at(X,Y) : not negative
	<- 	?carrying(vegetable,N);
		-+carrying(vegetable,N-1);
		planting_at(X,Y).

+!planting_at(X,Y) : negative 
	<-	true.
	